import React from 'react';
import { Card, Button, Space, Typography, Tooltip, Modal, message } from 'antd';
import {
  PlayCircleOutlined,
  PauseCircleOutlined,
  ReloadOutlined,
  DownloadOutlined,
  RedoOutlined,
  ArrowLeftOutlined,
  DeleteOutlined,
  EyeOutlined
} from '@ant-design/icons';
import { EnhancedScanTaskResponse } from '../../types/taskDetail';
import './TaskActionPanel.css';

const { Text, Title } = Typography;

interface TaskActionPanelProps {
  task: EnhancedScanTaskResponse;
  loading?: boolean;
  onAction: (action: 'start' | 'cancel' | 'retry' | 'delete' | 'download') => Promise<void>;
  onRefresh: () => void;
  onBack: () => void;
  onViewReport?: () => void;
}

const TaskActionPanel: React.FC<TaskActionPanelProps> = ({
  task,
  loading = false,
  onAction,
  onRefresh,
  onBack,
  onViewReport
}) => {

  // 获取任务可执行的操作
  const getAvailableActions = () => {
    const actions = {
      canStart: task.status === 'PENDING',
      canCancel: task.status === 'RUNNING',
      canRetry: task.status === 'FAILED' && (task.canRetry !== false),
      canDownload: ['COMPLETED', 'SUCCESS'].includes(task.status) && task.reportPath,
      canDelete: ['COMPLETED', 'FAILED', 'CANCELLED', 'SUCCESS'].includes(task.status),
      canViewReport: ['COMPLETED', 'SUCCESS'].includes(task.status)
    };
    return actions;
  };

  // 处理操作确认
  const handleActionWithConfirm = (action: 'start' | 'cancel' | 'retry' | 'delete', message: string) => {
    Modal.confirm({
      title: '确认操作',
      content: message,
      okText: '确定',
      cancelText: '取消',
      onOk: () => onAction(action)
    });
  };

  // 处理下载操作
  const handleDownload = async () => {
    try {
      await onAction('download');
      message.success('报告下载已开始');
    } catch (error) {
      message.error('下载失败，请稍后重试');
    }
  };

  const actions = getAvailableActions();

  return (
    <div className="task-action-panel">
      <Card
        title={
          <div className="panel-header">
            <Title level={5} style={{ margin: 0, color: '#1890ff' }}>
              任务操作
            </Title>
            <Text type="secondary" style={{ fontSize: 12 }}>
              任务ID: #{task.id}
            </Text>
          </div>
        }
        className="action-panel-card"
        bodyStyle={{ padding: '16px 20px' }}
      >
        <div className="action-section">
          <div className="section-title">
            <Text strong style={{ fontSize: 13, color: '#666' }}>
              任务控制
            </Text>
          </div>
          <Space direction="vertical" style={{ width: '100%' }} size="small">
            {actions.canStart && (
              <Tooltip title="启动任务执行" placement="left">
                <Button
                  type="primary"
                  icon={<PlayCircleOutlined />}
                  onClick={() => handleActionWithConfirm('start', '确定要启动这个扫描任务吗？')}
                  loading={loading}
                  block
                  style={{
                    background: '#52c41a',
                    borderColor: '#52c41a',
                    boxShadow: '0 2px 8px rgba(82, 196, 26, 0.3)'
                  }}
                >
                  启动任务
                </Button>
              </Tooltip>
            )}

            {actions.canCancel && (
              <Tooltip title="取消正在执行的任务" placement="left">
                <Button
                  icon={<PauseCircleOutlined />}
                  onClick={() => handleActionWithConfirm('cancel', '确定要取消正在执行的任务吗？')}
                  loading={loading}
                  block
                  style={{
                    background: '#faad14',
                    borderColor: '#faad14',
                    color: 'white'
                  }}
                >
                  取消任务
                </Button>
              </Tooltip>
            )}

            {actions.canRetry && (
              <Tooltip title={`重试任务 (${task.retryCount || 0}/${task.maxRetryCount || 3})`} placement="left">
                <Button
                  icon={<RedoOutlined />}
                  onClick={() => handleActionWithConfirm('retry', `确定要重试这个任务吗？当前重试次数: ${task.retryCount || 0}/${task.maxRetryCount || 3}`)}
                  loading={loading}
                  block
                  style={{
                    background: '#722ed1',
                    borderColor: '#722ed1',
                    color: 'white'
                  }}
                >
                  重试任务
                  {task.retryCount !== undefined && (
                    <span style={{ marginLeft: 4, fontSize: 11 }}>
                      ({task.retryCount}/{task.maxRetryCount || 3})
                    </span>
                  )}
                </Button>
              </Tooltip>
            )}
          </Space>
        </div>

        <div className="action-section">
          <div className="section-title">
            <Text strong style={{ fontSize: 13, color: '#666' }}>
              结果操作
            </Text>
          </div>
          <Space direction="vertical" style={{ width: '100%' }} size="small">
            {actions.canViewReport && onViewReport && (
              <Tooltip title="查看详细报告" placement="left">
                <Button
                  icon={<EyeOutlined />}
                  onClick={onViewReport}
                  block
                  type="dashed"
                >
                  查看报告
                </Button>
              </Tooltip>
            )}

            {actions.canDownload && (
              <Tooltip title="下载扫描报告" placement="left">
                <Button
                  type="primary"
                  icon={<DownloadOutlined />}
                  onClick={handleDownload}
                  block
                  style={{
                    background: '#1890ff',
                    borderColor: '#1890ff',
                    boxShadow: '0 2px 8px rgba(24, 144, 255, 0.3)'
                  }}
                >
                  下载报告
                </Button>
              </Tooltip>
            )}
          </Space>
        </div>

        <div className="action-section">
          <div className="section-title">
            <Text strong style={{ fontSize: 13, color: '#666' }}>
              其他操作
            </Text>
          </div>
          <Space direction="vertical" style={{ width: '100%' }} size="small">
            <Tooltip title="刷新任务状态" placement="left">
              <Button
                icon={<ReloadOutlined />}
                onClick={onRefresh}
                block
                type="default"
              >
                刷新状态
              </Button>
            </Tooltip>

            <Tooltip title="返回任务列表" placement="left">
              <Button
                icon={<ArrowLeftOutlined />}
                onClick={onBack}
                block
                type="default"
              >
                返回列表
              </Button>
            </Tooltip>

            {actions.canDelete && (
              <Tooltip title="删除任务（不可恢复）" placement="left">
                <Button
                  danger
                  icon={<DeleteOutlined />}
                  onClick={() => handleActionWithConfirm('delete', '确定要删除这个任务吗？删除后不可恢复！')}
                  loading={loading}
                  block
                  type="dashed"
                >
                  删除任务
                </Button>
              </Tooltip>
            )}
          </Space>
        </div>

        {/* 任务状态提示 */}
        <div className="status-hint">
          <Text type="secondary" style={{ fontSize: 11, lineHeight: 1.4 }}>
            {task.status === 'PENDING' && '任务已创建，等待启动执行'}
            {task.status === 'RUNNING' && `正在执行中... (${task.progress || 0}%)`}
            {task.status === 'COMPLETED' && '任务执行完成，可下载报告'}
            {task.status === 'SUCCESS' && '任务执行成功，可下载报告'}
            {task.status === 'FAILED' && task.canRetry !== false && '任务执行失败，可重试'}
            {task.status === 'FAILED' && task.canRetry === false && '任务执行失败，已达最大重试次数'}
            {task.status === 'CANCELLED' && '任务已被取消'}
          </Text>
        </div>
      </Card>
    </div>
  );
};

export default TaskActionPanel;